// 全局变量
let qrCodeInstance = null;
let currentCanvas = null;

// DOM元素
const elements = {
    textInput: null,
    charCount: null,
    qrSize: null,
    errorLevel: null,
    foregroundColor: null,
    backgroundColor: null,
    margin: null,
    marginValue: null,
    generateBtn: null,
    getCurrentUrl: null,
    clearInput: null,
    downloadPng: null,
    downloadSvg: null,
    qrcode: null,
    placeholder: null
};

// 初始化函数
document.addEventListener('DOMContentLoaded', function() {
    initializeElements();
    setupEventListeners();
    updateCharCount();
});

// 初始化DOM元素
function initializeElements() {
    elements.textInput = document.getElementById('textInput');
    elements.charCount = document.getElementById('charCount');
    elements.qrSize = document.getElementById('qrSize');
    elements.errorLevel = document.getElementById('errorLevel');
    elements.foregroundColor = document.getElementById('foregroundColor');
    elements.backgroundColor = document.getElementById('backgroundColor');
    elements.margin = document.getElementById('margin');
    elements.marginValue = document.getElementById('marginValue');
    elements.generateBtn = document.getElementById('generateBtn');
    elements.getCurrentUrl = document.getElementById('getCurrentUrl');
    elements.clearInput = document.getElementById('clearInput');
    elements.downloadPng = document.getElementById('downloadPng');
    elements.downloadSvg = document.getElementById('downloadSvg');
    elements.qrcode = document.getElementById('qrcode');
    elements.placeholder = document.getElementById('placeholder');
}

// 设置事件监听器
function setupEventListeners() {
    // 文本输入事件
    elements.textInput.addEventListener('input', updateCharCount);
    elements.textInput.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'Enter') {
            generateQRCode();
        }
    });

    // 边距滑块事件
    elements.margin.addEventListener('input', function() {
        elements.marginValue.textContent = this.value;
    });

    // 按钮事件
    elements.generateBtn.addEventListener('click', generateQRCode);
    elements.getCurrentUrl.addEventListener('click', getCurrentPageUrl);
    elements.clearInput.addEventListener('click', clearInput);
    elements.downloadPng.addEventListener('click', downloadAsPng);
    elements.downloadSvg.addEventListener('click', downloadAsSvg);

    // 参数变化时自动重新生成（如果已经生成过）
    [elements.qrSize, elements.errorLevel, elements.foregroundColor, 
     elements.backgroundColor, elements.margin].forEach(element => {
        element.addEventListener('change', function() {
            if (qrCodeInstance && elements.textInput.value.trim()) {
                generateQRCode();
            }
        });
    });
}

// 更新字符计数
function updateCharCount() {
    const count = elements.textInput.value.length;
    elements.charCount.textContent = count;
    
    // 字符数颜色提示
    if (count > 800) {
        elements.charCount.style.color = '#dc3545';
    } else if (count > 600) {
        elements.charCount.style.color = '#fd7e14';
    } else {
        elements.charCount.style.color = '#6c757d';
    }
}

// 获取当前页面URL
function getCurrentPageUrl() {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        if (tabs[0]) {
            elements.textInput.value = tabs[0].url;
            updateCharCount();
        }
    });
}

// 清空输入
function clearInput() {
    elements.textInput.value = '';
    updateCharCount();
    clearQRCode();
}

// 生成二维码
function generateQRCode() {
    const text = elements.textInput.value.trim();
    
    if (!text) {
        showNotification('请输入要生成二维码的内容', 'error');
        return;
    }
    
    if (text.length > 1000) {
        showNotification('内容过长，请控制在1000字符以内', 'error');
        return;
    }

    // 显示加载状态
    showLoading();
    
    try {
        // 清除之前的二维码
        clearQRCode();
        
        // 获取参数
        const options = {
            text: text,
            width: parseInt(elements.qrSize.value),
            height: parseInt(elements.qrSize.value),
            colorDark: elements.foregroundColor.value,
            colorLight: elements.backgroundColor.value,
            correctLevel: QRCode.CorrectLevel[elements.errorLevel.value],
            margin: parseInt(elements.margin.value)
        };
        
        // 生成二维码
        qrCodeInstance = new QRCode(elements.qrcode, options);
        
        // 隐藏占位符
        elements.placeholder.classList.add('hidden');
        
        // 启用下载按钮
        elements.downloadPng.disabled = false;
        elements.downloadSvg.disabled = false;
        
        // 获取生成的canvas
        setTimeout(() => {
            currentCanvas = elements.qrcode.querySelector('canvas');
            hideLoading();
            showNotification('二维码生成成功！', 'success');
        }, 100);
        
    } catch (error) {
        console.error('生成二维码失败:', error);
        hideLoading();
        showNotification('生成二维码失败，请检查输入内容', 'error');
    }
}

// 清除二维码
function clearQRCode() {
    if (qrCodeInstance) {
        elements.qrcode.innerHTML = '';
        qrCodeInstance = null;
        currentCanvas = null;
    }
    
    // 显示占位符
    elements.placeholder.classList.remove('hidden');
    
    // 禁用下载按钮
    elements.downloadPng.disabled = true;
    elements.downloadSvg.disabled = true;
}

// 下载PNG格式
function downloadAsPng() {
    if (!currentCanvas) {
        showNotification('请先生成二维码', 'error');
        return;
    }
    
    try {
        // 创建下载链接
        const link = document.createElement('a');
        link.download = `qrcode_${Date.now()}.png`;
        link.href = currentCanvas.toDataURL('image/png');
        link.click();
        
        showNotification('PNG文件下载成功！', 'success');
    } catch (error) {
        console.error('下载失败:', error);
        showNotification('下载失败，请重试', 'error');
    }
}

// 下载SVG格式
function downloadAsSvg() {
    if (!currentCanvas) {
        showNotification('请先生成二维码', 'error');
        return;
    }
    
    try {
        // 从canvas创建SVG
        const svg = canvasToSvg(currentCanvas);
        const blob = new Blob([svg], { type: 'image/svg+xml' });
        const url = URL.createObjectURL(blob);
        
        // 创建下载链接
        const link = document.createElement('a');
        link.download = `qrcode_${Date.now()}.svg`;
        link.href = url;
        link.click();
        
        // 清理URL
        URL.revokeObjectURL(url);
        
        showNotification('SVG文件下载成功！', 'success');
    } catch (error) {
        console.error('下载失败:', error);
        showNotification('下载失败，请重试', 'error');
    }
}

// 将Canvas转换为SVG
function canvasToSvg(canvas) {
    const ctx = canvas.getContext('2d');
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    const data = imageData.data;
    
    let svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">`;
    
    // 背景
    svg += `<rect width="100%" height="100%" fill="${elements.backgroundColor.value}"/>`;
    
    // 遍历像素数据创建矩形
    const blockSize = Math.floor(canvas.width / 33); // 估算模块大小
    
    for (let y = 0; y < canvas.height; y += blockSize) {
        for (let x = 0; x < canvas.width; x += blockSize) {
            const index = (y * canvas.width + x) * 4;
            const r = data[index];
            const g = data[index + 1];
            const b = data[index + 2];
            const a = data[index + 3];
            
            // 如果不是背景色，则添加矩形
            if (a > 0 && (r < 200 || g < 200 || b < 200)) {
                svg += `<rect x="${x}" y="${y}" width="${blockSize}" height="${blockSize}" fill="${elements.foregroundColor.value}"/>`;
            }
        }
    }
    
    svg += '</svg>';
    return svg;
}

// 显示加载状态
function showLoading() {
    elements.generateBtn.innerHTML = '<span class="loading"></span>生成中...';
    elements.generateBtn.disabled = true;
}

// 隐藏加载状态
function hideLoading() {
    elements.generateBtn.innerHTML = '生成二维码';
    elements.generateBtn.disabled = false;
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    notification.textContent = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'success' ? '#28a745' : type === 'error' ? '#dc3545' : '#007bff'};
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
        z-index: 10000;
        font-size: 14px;
        max-width: 300px;
        animation: slideIn 0.3s ease-out;
    `;
    
    document.body.appendChild(notification);
    
    // 自动移除通知
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes slideIn {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    
    @keyframes slideOut {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(style);

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl + Enter 生成二维码
    if (e.ctrlKey && e.key === 'Enter') {
        e.preventDefault();
        generateQRCode();
    }
    
    // Escape 清空输入
    if (e.key === 'Escape') {
        e.preventDefault();
        clearInput();
    }
});

// 保存设置到localStorage
function saveSettings() {
    const settings = {
        qrSize: elements.qrSize.value,
        errorLevel: elements.errorLevel.value,
        foregroundColor: elements.foregroundColor.value,
        backgroundColor: elements.backgroundColor.value,
        margin: elements.margin.value
    };
    
    localStorage.setItem('qrCodeSettings', JSON.stringify(settings));
}

// 加载设置从localStorage
function loadSettings() {
    const saved = localStorage.getItem('qrCodeSettings');
    if (saved) {
        try {
            const settings = JSON.parse(saved);
            elements.qrSize.value = settings.qrSize || '300';
            elements.errorLevel.value = settings.errorLevel || 'M';
            elements.foregroundColor.value = settings.foregroundColor || '#000000';
            elements.backgroundColor.value = settings.backgroundColor || '#FFFFFF';
            elements.margin.value = settings.margin || '4';
            elements.marginValue.textContent = elements.margin.value;
        } catch (e) {
            console.error('加载设置失败:', e);
        }
    }
}

// 页面加载时恢复设置
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(loadSettings, 100);
});

// 设置变化时保存
document.addEventListener('change', function(e) {
    if (e.target.matches('#qrSize, #errorLevel, #foregroundColor, #backgroundColor, #margin')) {
        saveSettings();
    }
}); 